//
//  RegionSettingViewController.m
//  location
//
//  Created by Dongxiang Xu on 2025/5/13.
//

#import "RegionSettingViewController.h"
#import "RegionSearchController.h"
#import "XDXMapView.h"
#import "RegionLocationTableViewCell.h"
#import "RegionLocationAnnotation.h"
#import "TrackEventAnnotationView.h"
#import "RegionMemberTableViewCell.h"
#import "TrackTool.h"

@interface RegionSettingViewController ()<MKMapViewDelegate,UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>

@property (nonatomic, strong) UIImageView *loImg;
@property (nonatomic, strong) UIView *loCircle;
@property (nonatomic, strong) NSMutableArray *orginalNotification;
@property (nonatomic, strong) NSString *avatar;
@property (nonatomic, strong) XDXMapView *mapView;
@property (nonatomic, strong) UIButton *save;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) UIButton *location;
@property (nonatomic, strong) UILabel *lastLog;
@property (nonatomic, strong) UIView *sliderView;
@property (nonatomic, strong) UISlider *slider;
@property (nonatomic, strong) UIView *radiusView;
@property (nonatomic, strong) UILabel *radius;
@property (nonatomic, strong) UIVisualEffectView *visualEffect;
@property (nonatomic, strong) UIBezierPath *cornerRadiusPath;
@property (nonatomic, strong) CAShapeLayer *cornerRadiusLayer;
@property (nonatomic, strong) CAShapeLayer *borderLayer;
@property (nonatomic, strong) UIView *infoView;
@property (nonatomic, strong) UITextField *textField;
@property (nonatomic, strong) UILabel *line;
@property (nonatomic, strong) MKPointAnnotation *annotation;
@property (nonatomic, assign) CGFloat annotationWidth;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIImpactFeedbackGenerator *feedbackGen;
@property (nonatomic, assign) float lastFeedbackValue;
@property (nonatomic, assign) CGFloat lastContentOffsetY;

@end

@implementation RegionSettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    if (self.locationInfo) {
        if (![self.locationInfo[@"avatar"] isKindOfClass:[NSString class]] || [self.locationInfo[@"avatar"] length]==0) {
            _avatar = @"region_icon_1";
        }else{
            _avatar = [NSString stringWithFormat:@"%@",self.locationInfo[@"avatar"]];
        }
        self.orginalNotification = [NSMutableArray array];
        for (NSMutableDictionary *user in self.locationInfo[@"usersNotification"]) {
            NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:user];
            [self.orginalNotification addObject:dic];
        }
    }else{
        _avatar = @"region_icon_1";
    }
    
    self.view.backgroundColor = RealWhiteColor;
    self.mapView = [[XDXMapView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-388)];
    self.mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.mapView.delegate = self;
    self.mapView.showsUserLocation = YES;
    self.mapView.zoomLevel = 15;
    self.mapView.userTrackingMode = MKUserTrackingModeNone;
    self.mapView.rotateEnabled = NO;
    self.mapView.layer.masksToBounds = NO;
    self.mapView.showsBuildings = YES;
    [self.view addSubview:self.mapView];
    
    _annotationWidth = 52;
    _loCircle = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 52, 52)];
    _loCircle.userInteractionEnabled = NO;
    [_loCircle.layer setCornerRadius:26];
    [_loCircle.layer setBorderWidth:1];
    [_loCircle.layer setBorderColor:NormalMainColor.CGColor];
    _loCircle.backgroundColor = [NormalMainColor colorWithAlphaComponent:0.15];
    _loCircle.center = self.mapView.center;
    _loCircle.y = _loCircle.y+16;
    [self.view addSubview:_loCircle];
    
    _loImg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 32, 32)];
    _loImg.image = [UIImage imageNamed:@"region_location"];
    _loImg.contentMode = UIViewContentModeScaleAspectFit;
    _loImg.center = self.mapView.center;
    [self.view addSubview:_loImg];
    
    UIButton *popButton = [[UIButton alloc] initWithFrame:CGRectMake(0, STATUSHEIGHT, 46, 36)];
    [popButton setImage:[UIImage imageNamed:@"nav_back"] forState:UIControlStateNormal];
    [self.view addSubview:popButton];
    [[popButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self.locationInfo setValue:self.orginalNotification forKey:@"usersNotification"];
        [self.navigationController popViewControllerAnimated:YES];
    }];

    _save = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-72, STATUSHEIGHT+9, 56, 32)];
    _save.backgroundColor = NormalMainColor;
    [_save.layer setCornerRadius:8];
    [_save setTitle:@"保存" forState:UIControlStateNormal];
    [_save setTitleColor:RealWhiteColor forState:UIControlStateNormal];
    [_save.titleLabel setFont:MEDIUM_FONT(15)];
    [self.view addSubview:_save];
    [[_save rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self saveNetwork];
    }];
    
    _infoView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT-413, SCREEN_WIDTH, SCREEN_HEIGHT)];
    [self.view addSubview:_infoView];
    
    CALayer *infoLayer = [CALayer layer];
    infoLayer.frame = _infoView.bounds;
    infoLayer.cornerRadius = 25;
    infoLayer.masksToBounds = NO;
    infoLayer.backgroundColor = RealWhiteColor.CGColor;
    infoLayer.shadowColor = RealBlackColor.CGColor;
    infoLayer.shadowOffset = CGSizeMake(0,2);
    infoLayer.shadowOpacity = 0.3;
    infoLayer.shadowRadius = 3;
    [_infoView.layer addSublayer:infoLayer];
    
    
    
    
    _sliderView = [[UIView alloc] initWithFrame:CGRectMake(0, _infoView.y-98, SCREEN_WIDTH, 98)];
    [self.view addSubview:_sliderView];
    
    UIView *sliderBg = [[UIView alloc] initWithFrame:CGRectMake(17, 68, SCREEN_WIDTH-34, 8)];
    sliderBg.hidden = YES;
    [_sliderView addSubview:sliderBg];
    
    CALayer *sliderLayer = [CALayer layer];
    sliderLayer.frame = sliderBg.bounds;
    sliderLayer.cornerRadius = 4;
    sliderLayer.masksToBounds = NO;
    sliderLayer.backgroundColor = RealWhiteColor.CGColor;
    sliderLayer.shadowColor = RealBlackColor.CGColor;
    sliderLayer.shadowOffset = CGSizeMake(0,2);
    sliderLayer.shadowOpacity = 0.3;
    sliderLayer.shadowRadius = 3;
    [sliderBg.layer addSublayer:sliderLayer];
    
    _slider = [[UISlider alloc] initWithFrame:CGRectMake(18, 56, SCREEN_WIDTH-36, 32)];
    _slider.minimumValue = 100;
    _slider.maximumValue = 2000;
    _slider.minimumTrackTintColor = NormalMainColor;
    _slider.maximumTrackTintColor = RealWhiteColor;
    [_slider setThumbImage:[UIImage imageNamed:@"track_image"] forState:UIControlStateNormal];
    _slider.hidden = YES;
    [_slider addTarget:self action:@selector(sliderTouchDown:) forControlEvents:UIControlEventTouchDown];
    [_slider addTarget:self action:@selector(sliderTouchUp:) forControlEvents:UIControlEventTouchUpInside | UIControlEventTouchUpOutside];
    [_slider addTarget:self action:@selector(sliderValueChanged:) forControlEvents:UIControlEventValueChanged];
    [_sliderView addSubview:_slider];
    if (self.locationInfo) {
        _slider.value = [self.locationInfo[@"radius"] integerValue];
    }else{
        _slider.value = 150;
    }
    
    _radiusView = [[UIView alloc] initWithFrame:CGRectMake(0, _slider.y-28, 60, 28)];
    _radiusView.hidden = YES;
    [_sliderView addSubview:_radiusView];
    _radiusView.layer.masksToBounds = NO;
    _radiusView.layer.shadowColor   = RealBlackColor.CGColor;
    _radiusView.layer.shadowOpacity = 0.2;
    _radiusView.layer.shadowRadius  = 3.0;
    _radiusView.layer.shadowOffset  = CGSizeMake(0, 2);
    
    _visualEffect = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight]];
    _visualEffect.frame = CGRectMake(0, 0, _radiusView.width, _radiusView.height);
    [_radiusView addSubview:_visualEffect];
            
    _cornerRadiusPath = [UIBezierPath bezierPathWithRoundedRect:_visualEffect.bounds byRoundingCorners:UIRectCornerTopRight | UIRectCornerTopLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(8, 8)];
    
    _cornerRadiusLayer = [CAShapeLayer layer];
    _cornerRadiusLayer.frame = _visualEffect.bounds;
    _cornerRadiusLayer.path = _cornerRadiusPath.CGPath;
    _visualEffect.layer.mask = _cornerRadiusLayer;
    
    _borderLayer = [CAShapeLayer layer];
    _borderLayer.path = _cornerRadiusPath.CGPath;
    _borderLayer.fillColor = [UIColor clearColor].CGColor;
    _borderLayer.strokeColor = RealWhiteColor.CGColor;
    _borderLayer.lineWidth = 1.0;
    [_visualEffect.layer addSublayer:_borderLayer];
    
    _radius = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, _radiusView.width, _radiusView.height)];
    _radius.textAlignment = NSTextAlignmentCenter;
    _radius.font = MEDIUM_FONT(14);
    _radius.textColor = RealBlackColor;
    [_radiusView addSubview:_radius];

    _location = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-56, 0, 40, 40)];
    [_sliderView addSubview:_location];
    [[_location rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self.mapView rotateMapToNorthAnimated:YES Coordinate:self.mapView.userLocation.coordinate];
    }];
    CALayer *locationLayer = [CALayer layer];
    locationLayer.frame = self.location.bounds;
    locationLayer.cornerRadius = 16;
    locationLayer.masksToBounds = NO;
    locationLayer.backgroundColor = RealWhiteColor.CGColor;
    locationLayer.shadowColor = RealBlackColor.CGColor;
    locationLayer.shadowOffset = CGSizeMake(0,2);
    locationLayer.shadowOpacity = 0.3;
    locationLayer.shadowRadius = 3;
    [self.location.layer addSublayer:locationLayer];
    UIImageView *locationImg = [[UIImageView alloc] initWithFrame:CGRectMake((self.location.width-22)/2, (self.location.height-22)/2, 22, 22)];
    locationImg.image = [UIImage imageNamed:@"back_location"];
    [self.location addSubview:locationImg];
    
    if (self.locationInfo) {
        if ([self.groupInfo[@"adminId"] integerValue] == [XDXShareInstance shareInstance].userId.integerValue || [self.locationInfo[@"adminId"] integerValue] == [XDXShareInstance shareInstance].userId.integerValue){
            _slider.hidden = NO;
            sliderBg.hidden = NO;
            _radiusView.hidden = NO;
        }
    }else{
        _slider.hidden = NO;
        sliderBg.hidden = NO;
        _radiusView.hidden = NO;
    }
    
    
    _line = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, _infoView.width, 4)];
    _line.backgroundColor = LightBGColor;
    [_infoView addSubview:_line];
    
    if (!self.locationInfo || (self.locationInfo && ([self.groupInfo[@"adminId"] integerValue] == [XDXShareInstance shareInstance].userId.integerValue || [self.locationInfo[@"adminId"] integerValue] == [XDXShareInstance shareInstance].userId.integerValue))) {
        UIView *inputView = [[UIView alloc] initWithFrame:CGRectMake(16, 32, _infoView.width-32, 50)];
        inputView.backgroundColor = LightBGColor;
        inputView.layer.masksToBounds = YES;
        [inputView.layer setCornerRadius:16];
        [_infoView addSubview:inputView];
        
        UIButton *mapImg = [[UIButton alloc] initWithFrame:CGRectMake(12, (inputView.height-38)/2, 38, 38)];
        [mapImg setImage:[UIImage imageNamed:_avatar] forState:UIControlStateNormal];
        [inputView addSubview:mapImg];
        UIAction *home = [UIAction actionWithTitle:@"家" image:[UIImage imageNamed:@"region_icon_0"] identifier:nil handler:^(__kindof UIAction * _Nonnull action) {
            self.avatar = @"region_icon_0";
            self.textField.placeholder = @"家";
            [mapImg setImage:[UIImage imageNamed:self.avatar] forState:UIControlStateNormal];
        }];
        UIAction *location = [UIAction actionWithTitle:@"位置" image:[UIImage imageNamed:@"region_icon_1"] identifier:nil handler:^(__kindof UIAction * _Nonnull action) {
            self.avatar = @"region_icon_1";
            [mapImg setImage:[UIImage imageNamed:self.avatar] forState:UIControlStateNormal];
            self.textField.placeholder = @"位置";
        }];
        UIAction *work = [UIAction actionWithTitle:@"工作地点" image:[UIImage imageNamed:@"region_icon_2"] identifier:nil handler:^(__kindof UIAction * _Nonnull action) {
            self.avatar = @"region_icon_2";
            [mapImg setImage:[UIImage imageNamed:self.avatar] forState:UIControlStateNormal];
            self.textField.placeholder = @"工作地点";
        }];
        UIAction *lovePlace = [UIAction actionWithTitle:@"宝藏小店" image:[UIImage imageNamed:@"region_icon_7"] identifier:nil handler:^(__kindof UIAction * _Nonnull action) {
            self.avatar = @"region_icon_7";
            [mapImg setImage:[UIImage imageNamed:self.avatar] forState:UIControlStateNormal];
            self.textField.placeholder = @"宝藏小店";
        }];
        UIAction *notification = [UIAction actionWithTitle:@"提醒" image:[UIImage imageNamed:@"region_icon_4"] identifier:nil handler:^(__kindof UIAction * _Nonnull action) {
            self.avatar = @"region_icon_4";
            [mapImg setImage:[UIImage imageNamed:self.avatar] forState:UIControlStateNormal];
            self.textField.placeholder = @"提醒";
        }];
        UIAction *collect = [UIAction actionWithTitle:@"打卡" image:[UIImage imageNamed:@"region_icon_5"] identifier:nil handler:^(__kindof UIAction * _Nonnull action) {
            self.avatar = @"region_icon_5";
            [mapImg setImage:[UIImage imageNamed:self.avatar] forState:UIControlStateNormal];
            self.textField.placeholder = @"打卡";
        }];
       
       
        mapImg.menu = [UIMenu menuWithTitle:@"" children:@[home,location,work,notification,collect,lovePlace]];
        mapImg.showsMenuAsPrimaryAction = YES;
            
        UILabel *inputLine = [[UILabel alloc] initWithFrame:CGRectMake(mapImg.maxX+8, (inputView.height-18)/2, 2, 18)];
        inputLine.backgroundColor = RealBlackColor;
        [inputView addSubview:inputLine];
        
        _textField = [[UITextField alloc] initWithFrame:CGRectMake(inputLine.maxX+12, 0, inputView.width-inputLine.maxX-24, inputView.height)];
        _textField.textColor = RealBlackColor;
        _textField.tintColor = NormalMainColor;
        _textField.font = REAL_MEDIUM_FONT(18);
        _textField.returnKeyType = UIReturnKeyDone;
        _textField.delegate = self;
        [_textField addTarget:self action:@selector(textChangeEvent:) forControlEvents:UIControlEventEditingChanged];
        if ([_avatar isEqualToString:@"region_icon_0"]) {
            _textField.placeholder = @"家";
        }else if ([_avatar isEqualToString:@"region_icon_1"]){
            _textField.placeholder = @"位置";
        }else if ([_avatar isEqualToString:@"region_icon_2"]){
            _textField.placeholder = @"工作地点";
        }else if ([_avatar isEqualToString:@"region_icon_4"]){
            _textField.placeholder = @"提醒";
        }else if ([_avatar isEqualToString:@"region_icon_5"]){
            _textField.placeholder = @"大卡";
        }else if ([_avatar isEqualToString:@"region_icon_7"]){
            _textField.placeholder = @"宝藏小店";
        }
       
        [inputView addSubview:_textField];
        
        UIView *addressView = [[UIView alloc] initWithFrame:CGRectMake(0, inputView.maxY+8, _infoView.width, 50)];
        [_infoView addSubview:addressView];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
        [[tap rac_gestureSignal] subscribeNext:^(id x) {
            RegionSearchController *vc = [[RegionSearchController alloc] init];
            MKCoordinateSpan newRegionSpan = MKCoordinateSpanMake(360 / pow(2, 1), 360 / pow(2, 1));
            MKCoordinateRegion newRegion = MKCoordinateRegionMake(self.mapView.centerCoordinate, newRegionSpan);
            vc.region = newRegion;
            vc.modalPresentationStyle = UIModalPresentationFullScreen;
            [self presentViewController:vc animated:YES completion:nil];
            vc.RegionSearchBlock = ^(MKMapItem *item) {
                self.textField.text = item.name;
                [self.mapView rotateMapToNorthAnimated:YES Coordinate:item.placemark.coordinate];
            };
        }];
        [addressView addGestureRecognizer:tap];
            
        UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(16, 0, _infoView.width-32, 26)];
        nameLabel.font = MEDIUM_FONT(14);
        nameLabel.textColor = ThemeDark2;
        nameLabel.text = @"位置信息";
        [addressView addSubview:nameLabel];
        
        _lastLog = [[UILabel alloc] initWithFrame:CGRectMake(16, nameLabel.maxY, _infoView.width-52, 24)];
        _lastLog.textColor = GraryHeavyLightColor;
        _lastLog.font = DEFAULT_FONT(14);
        [addressView addSubview:_lastLog];
        
        UIImageView *search = [[UIImageView alloc]initWithFrame:CGRectMake(_lastLog.maxX, nameLabel.maxY+3, 18, 18)];
        search.image = [UIImage imageNamed:@"search"];
        [addressView addSubview:search];
        
        _line.y = addressView.maxY+20;
    }else{
        UIButton *img = [[UIButton alloc] initWithFrame:CGRectMake(16, 33, 60, 60)];
        [img setImage:[UIImage imageNamed:self.locationInfo[@"avatar"]] forState:UIControlStateNormal];
        img.layer.masksToBounds = YES;
        img.backgroundColor = WhiteColor;
        [img.layer setCornerRadius:24];
        [_infoView addSubview:img];
        
        UILabel *name = [[UILabel alloc] initWithFrame:CGRectMake(img.maxX+16, 39, _infoView.width-img.maxX-32, 24)];
        name.textColor = RealBlackColor;
        name.font = MEDIUM_FONT(16);
        name.text = [NSString stringWithFormat:@"%@",self.locationInfo[@"name"]];
        [_infoView addSubview:name];
                
        UILabel *address = [[UILabel alloc] initWithFrame:CGRectMake(img.maxX+16, name.maxY+4, _infoView.width-img.maxX-32, 20)];
        address.textColor = GraryLightColor;
        address.font = DEFAULT_FONT(14);
        address.text = [NSString stringWithFormat:@"%@",self.locationInfo[@"address"]];
        [_infoView addSubview:address];
                        
        _line.y = img.maxY+20;
    }
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, _line.maxY, SCREEN_WIDTH, SCREEN_HEIGHT-_infoView.y-_line.maxY) style:UITableViewStylePlain];
    _tableView.separatorStyle  = UITableViewCellSeparatorStyleNone;
    _tableView.estimatedRowHeight = 0;
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    if (@available(iOS 15.0, *)) {
        _tableView.fillerRowHeight = 0;
        _tableView.sectionHeaderTopPadding = 0;
    }
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.showsHorizontalScrollIndicator = NO;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = RealWhiteColor;
    [_infoView addSubview:_tableView];
    
    if ([self.locationInfo[@"usersNotification"] count]>0 || [self.groupInfo[@"userInfo"] count]>0) {
        UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(16, 20, SCREEN_WIDTH-32, 16)];
        label.font = REAL_MEDIUM_FONT(14);
        label.textColor = RealBlackColor;
        label.text = @"通知我";
        [headerView addSubview:label];
        _tableView.tableHeaderView = headerView;
    }
    
    if (self.locationInfo) {
        if ([self.groupInfo[@"adminId"] integerValue] == [XDXShareInstance shareInstance].userId.integerValue || [self.locationInfo[@"adminId"] integerValue] == [XDXShareInstance shareInstance].userId.integerValue){
            UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 106)];
            
            UIButton *delete = [[UIButton alloc] initWithFrame:CGRectMake(16, 16, SCREEN_WIDTH-32, 56)];
            [delete setBackgroundImage:[UIImage imageNamed:@"delete"] forState:UIControlStateNormal];
            [delete setBackgroundImage:[UIImage imageNamed:@"delete_high"] forState:UIControlStateHighlighted];
            [footerView addSubview:delete];
            [[delete rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
                NSString *string = [NSString stringWithFormat:@"确定要删除 “%@” 吗？",self.locationInfo[@"name"]];
                UIAlertController *ac = [UIAlertController alertControllerWithTitle:string
                                                                            message:@"将为您的整个家庭删除这个位置"
                                                                     preferredStyle:UIAlertControllerStyleActionSheet];
                NSMutableAttributedString *attrTitle = [[NSMutableAttributedString alloc] initWithString:string];
                [attrTitle addAttribute:NSFontAttributeName value:MEDIUM_FONT(17) range:NSMakeRange(0, attrTitle.length)];
                [ac setValue:attrTitle forKey:@"attributedTitle"];
                [ac addAction:[UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                    
                    NSDictionary *param = [NSMutableDictionary dictionary];
                    [param setValue:self.locationInfo[@"id"] forKey:@"locationId"];
                    CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
                    [manager encryptedPOST:@"/system/group/removegeofence"
                    parameters:param
                    success:^(NSDictionary *responseObject) {
                        if ([responseObject[@"code"] integerValue]==200) {
                            [self.navigationController popViewControllerAnimated:YES];
                            [[HCToast shareInstance] showToast:@"删除成功"];
                            if (self.RegionSettingBlock) {
                                self.RegionSettingBlock();
                            }
                        }
                    }
                    failure:^(NSError *aError) {
                        
                    }];
                }]];
                [ac addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
                UIPopoverPresentationController *pop = ac.popoverPresentationController;
                
                pop.sourceView = delete;
                pop.sourceRect = delete.bounds;
                pop.permittedArrowDirections = 0;
                [self presentViewController:ac animated:YES completion:nil];
            }];
            
            _tableView.tableFooterView = footerView;
        }
    }
    
    if (self.locationInfo) {
        CLLocationCoordinate2D coord = CLLocationCoordinate2DMake([self.locationInfo[@"latitude"] doubleValue],[self.locationInfo[@"longitude"] doubleValue]);
        [self.mapView setCenterCoordinate:coord];
        self.textField.text = [NSString stringWithFormat:@"%@",self.locationInfo[@"name"]];
        self.lastLog.text = [NSString stringWithFormat:@"%@",self.locationInfo[@"address"]];
    }else{
        [self.mapView setCenterCoordinate:self.mapView.userLocation.coordinate animated:NO];
    }
    
    if (_aCoordinate.latitude>0 && _aCoordinate.longitude>0) {
        [self.mapView rotateMapToNorthAnimated:YES Coordinate:_aCoordinate];
    }
    
    CGFloat x = [_slider thumbRectForBounds:CGRectMake(0, 0, 6, 6) trackRect:_slider.frame value:_slider.value].origin.x;
    if ((_slider.x+x+_radiusView.width)>SCREEN_WIDTH) {
        self.radiusView.x =  self.slider.x+x-self.radiusView.width;
        _cornerRadiusPath = [UIBezierPath bezierPathWithRoundedRect:_visualEffect.bounds byRoundingCorners:UIRectCornerTopRight | UIRectCornerTopLeft | UIRectCornerBottomLeft cornerRadii:CGSizeMake(8, 8)];
        
        _cornerRadiusLayer = [CAShapeLayer layer];
        _cornerRadiusLayer.frame = _visualEffect.bounds;
        _cornerRadiusLayer.path = _cornerRadiusPath.CGPath;
        _visualEffect.layer.mask = _cornerRadiusLayer;
        
        [_borderLayer removeFromSuperlayer];
        _borderLayer = nil;
        _borderLayer = [CAShapeLayer layer];
        _borderLayer.path = _cornerRadiusPath.CGPath;
        _borderLayer.fillColor = [UIColor clearColor].CGColor;
        _borderLayer.strokeColor = RealWhiteColor.CGColor;
        _borderLayer.lineWidth = 1.0;
        [_visualEffect.layer addSublayer:_borderLayer];
    }else{
        self.radiusView.x = self.slider.x+x;
        _cornerRadiusPath = [UIBezierPath bezierPathWithRoundedRect:_visualEffect.bounds byRoundingCorners:UIRectCornerTopRight | UIRectCornerTopLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(8, 8)];
        
        _cornerRadiusLayer = [CAShapeLayer layer];
        _cornerRadiusLayer.frame = _visualEffect.bounds;
        _cornerRadiusLayer.path = _cornerRadiusPath.CGPath;
        _visualEffect.layer.mask = _cornerRadiusLayer;
        
        [_borderLayer removeFromSuperlayer];
        _borderLayer = nil;
        _borderLayer = [CAShapeLayer layer];
        _borderLayer.path = _cornerRadiusPath.CGPath;
        _borderLayer.fillColor = [UIColor clearColor].CGColor;
        _borderLayer.strokeColor = RealWhiteColor.CGColor;
        _borderLayer.lineWidth = 1.0;
        [_visualEffect.layer addSublayer:_borderLayer];
    }
    _radius.text = [NSString stringWithFormat:@"%dm",(int)_slider.value];
}

- (void)saveNetwork
{
    if (self.locationInfo) {
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        [param setValue:self.locationInfo[@"id"] forKey:@"id"];
        [param setValue:self.groupInfo[@"id"] forKey:@"groupId"];
        [param setValue:[NSString stringWithFormat:@"%f",self.mapView.centerCoordinate.latitude] forKey:@"latitude"];
        [param setValue:[NSString stringWithFormat:@"%f",self.mapView.centerCoordinate.longitude] forKey:@"longitude"];
        [param setValue:[NSString stringWithFormat:@"%d",(int)self.slider.value] forKey:@"radius"];
        if (self.textField.text.length>0) {
            [param setValue:self.textField.text forKey:@"name"];
        }else{
            [param setValue:_textField.placeholder forKey:@"name"];
        }
        [param setValue:self.lastLog.text forKey:@"address"];
        [param setValue:self.avatar forKey:@"avatar"];
        CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
        [manager encryptedPUT:@"/system/group/editgeofence"
        parameters:param
        success:^(NSDictionary *responseObject) {
            if ([responseObject[@"code"] integerValue]==200) {
                NSMutableArray *param = [NSMutableArray array];
                for (NSDictionary *user in self.locationInfo[@"usersNotification"]) {
                    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
                    [dic setValue:self.locationInfo[@"id"] forKey:@"locationId"];
                    [dic setValue:user[@"userId"] forKey:@"monitoredUserId"];
                    [dic setValue:user[@"code"] forKey:@"code"];
                    [param addObject:dic];
                }
                CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
                [manager encryptedPUT:@"/system/group/editgroupuserlocationsetting"
                parameters:param
                success:^(NSDictionary *responseObject) {
                    [self.navigationController popViewControllerAnimated:YES];
                    if (self.RegionSettingBlock) {
                        self.RegionSettingBlock();
                    }
                }
                failure:^(NSError *aError) {
                    
                }];
            }
        }
        failure:^(NSError *aError) {
            
        }];
    }else{
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        [param setValue:self.groupInfo[@"id"] forKey:@"groupId"];
        [param setValue:[NSString stringWithFormat:@"%f",self.mapView.centerCoordinate.latitude] forKey:@"latitude"];
        [param setValue:[NSString stringWithFormat:@"%f",self.mapView.centerCoordinate.longitude] forKey:@"longitude"];
        [param setValue:[NSString stringWithFormat:@"%d",(int)self.slider.value] forKey:@"radius"];
        if (self.textField.text.length>0) {
            [param setValue:self.textField.text forKey:@"name"];
        }else{
            [param setValue:_textField.placeholder forKey:@"name"];
        }
        [param setValue:self.lastLog.text forKey:@"address"];
        [param setValue:self.avatar forKey:@"avatar"];
        CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
        [manager encryptedPOST:@"/system/group/geofence"
                    parameters:param
                       success:^(NSDictionary *responseObject) {
            if ([responseObject[@"code"] integerValue]==200) {
                NSString *locationId = responseObject[@"data"];
                NSMutableDictionary *param = [NSMutableDictionary dictionary];
                [param setValue:locationId forKey:@"locationId"];
                CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
                [manager encryptedPOST:@"/system/group/locationsetting"
                            parameters:param
                success:^(NSDictionary *responseObject) {
                    if ([responseObject[@"code"] integerValue]==200) {
                        self.locationInfo = [NSMutableDictionary dictionaryWithDictionary:responseObject[@"data"][@"locationInfo"]];
                        NSMutableArray *param = [NSMutableArray array];
                        for (NSDictionary *user in self.groupInfo[@"userInfo"]) {
                            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
                            [dic setValue:self.locationInfo[@"id"] forKey:@"locationId"];
                            [dic setValue:user[@"userId"] forKey:@"monitoredUserId"];
                            [dic setValue:user[@"code"] forKey:@"code"];
                            [param addObject:dic];
                        }
                        CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
                        [manager encryptedPUT:@"/system/group/editgroupuserlocationsetting"
                                   parameters:param
                        success:^(NSDictionary *responseObject) {
                            [self.navigationController popViewControllerAnimated:YES];
                            if (self.RegionSettingBlock) {
                                self.RegionSettingBlock();
                            }
                        }
                        failure:^(NSError *aError) {
                            
                        }];
                    }
                }
                failure:^(NSError *aError) {
                    
                }];
            }
        }
        failure:^(NSError *aError) {
            
        }];
    }
}

- (void)sliderTouchDown:(UISlider *)sender {
    if (@available(iOS 10.0, *)) {
        self.feedbackGen = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleLight];
        [self.feedbackGen prepare];
        self.lastFeedbackValue = sender.value;
    }
}

- (void)sliderTouchUp:(UISlider *)sender {
     self.feedbackGen = nil;
 }

- (void)sliderValueChanged:(UISlider *)slider
{
    float delta = fabsf(slider.value - self.lastFeedbackValue);
    // 控制“线性”频率，值变化到一定程度再震一次
    if (delta >= 100) { // 阈值可自行调节
        [self.feedbackGen impactOccurred];
        [self.feedbackGen prepare];      // 预热下一次
        self.lastFeedbackValue = slider.value;
    }
    
    RegionLocationAnnotation *annotationView = (RegionLocationAnnotation *)[self.mapView viewForAnnotation:self.annotation];
    double scale = slider.value/150.0;
    self.annotationWidth = 52*scale;
    CLLocationCoordinate2D loc = [self.mapView convertPoint:CGPointMake(0, 0) toCoordinateFromView:self.mapView];
    double distance = [TrackTool distanceBetweenOrderByLatitudeA:loc.latitude latitudeB:self.mapView.centerCoordinate.latitude longitudeA:loc.longitude longitudeB:self.mapView.centerCoordinate.longitude];
    double aScale = 1.52/distance;
    if (self.mapView.height==(SCREEN_HEIGHT-538)) {
        aScale = 1.3/distance;
    }
    [annotationView setBounds:CGRectMake(0, 0, self.annotationWidth*aScale, self.annotationWidth*aScale)];
    [annotationView.layer setCornerRadius:(self.annotationWidth*aScale)/2];
    [annotationView.location setFrame:CGRectMake((annotationView.width-52)/2, (annotationView.height-52)/2-25, 52, 52)];
        
    self.loCircle.width = self.annotationWidth*aScale;
    self.loCircle.height = self.annotationWidth*aScale;
    [self.loCircle.layer setCornerRadius:(self.annotationWidth*aScale)/2];
    self.loCircle.center = self.mapView.center;
    self.loCircle.y = self.loCircle.y+16;

   
    CGFloat x = [slider thumbRectForBounds:CGRectMake(0, 0, 6, 6) trackRect:slider.frame value:slider.value].origin.x;
    if ((slider.x+x+self.radiusView.width)>SCREEN_WIDTH) {
        self.radiusView.x =  slider.x+x-self.radiusView.width;
        _cornerRadiusPath = [UIBezierPath bezierPathWithRoundedRect:_visualEffect.bounds byRoundingCorners:UIRectCornerTopRight | UIRectCornerTopLeft | UIRectCornerBottomLeft cornerRadii:CGSizeMake(8, 8)];
        
        _cornerRadiusLayer = [CAShapeLayer layer];
        _cornerRadiusLayer.frame = _visualEffect.bounds;
        _cornerRadiusLayer.path = _cornerRadiusPath.CGPath;
        _visualEffect.layer.mask = _cornerRadiusLayer;
        
        [_borderLayer removeFromSuperlayer];
        _borderLayer = nil;
        _borderLayer = [CAShapeLayer layer];
        _borderLayer.path = _cornerRadiusPath.CGPath;
        _borderLayer.fillColor = [UIColor clearColor].CGColor;
        _borderLayer.strokeColor = RealWhiteColor.CGColor;
        _borderLayer.lineWidth = 1.0;
        [_visualEffect.layer addSublayer:_borderLayer];
    }else{
        self.radiusView.x = slider.x+x;
        _cornerRadiusPath = [UIBezierPath bezierPathWithRoundedRect:_visualEffect.bounds byRoundingCorners:UIRectCornerTopRight | UIRectCornerTopLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(8, 8)];
        
        _cornerRadiusLayer = [CAShapeLayer layer];
        _cornerRadiusLayer.frame = _visualEffect.bounds;
        _cornerRadiusLayer.path = _cornerRadiusPath.CGPath;
        _visualEffect.layer.mask = _cornerRadiusLayer;
        
        [_borderLayer removeFromSuperlayer];
        _borderLayer = nil;
        _borderLayer = [CAShapeLayer layer];
        _borderLayer.path = _cornerRadiusPath.CGPath;
        _borderLayer.fillColor = [UIColor clearColor].CGColor;
        _borderLayer.strokeColor = RealWhiteColor.CGColor;
        _borderLayer.lineWidth = 1.0;
        [_visualEffect.layer addSublayer:_borderLayer];
    }
    _radius.text = [NSString stringWithFormat:@"%dm",(int)slider.value];
    
    MKMapCamera *oldCamera = self.mapView.camera;
    MKMapCamera *newCamera = [MKMapCamera cameraLookingAtCenterCoordinate:self.mapView.centerCoordinate
                                                             fromDistance:slider.value*10
                                                                    pitch:oldCamera.pitch
                                                                  heading:0.0];
    [self.mapView setCamera:newCamera animated:YES];
    
   
}

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MKUserLocation class]]) {
        static NSString *customReuseIndetifier = @"TrackEventAnnotationView";
        
        TrackEventAnnotationView *annotationView = (TrackEventAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:customReuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[TrackEventAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:customReuseIndetifier];
            annotationView.canShowCallout = NO;
            annotationView.draggable = NO;
            annotationView.calloutOffset = CGPointMake(0, -5);
        }
        annotationView.hidden = YES;
        return annotationView;
    }else{
        static NSString *customReuseIndetifier = @"RegionLocationAnnotation";
        
        RegionLocationAnnotation *annotationView = (RegionLocationAnnotation *)[mapView dequeueReusableAnnotationViewWithIdentifier:customReuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[RegionLocationAnnotation alloc] initWithAnnotation:annotation reuseIdentifier:customReuseIndetifier];
            annotationView.canShowCallout = NO;
            annotationView.draggable = NO;
            annotationView.calloutOffset = CGPointMake(0, -5);
        }
        
        return annotationView;
    }
}

- (void)mapViewDidChangeVisibleRegion:(MKMapView *)mapView
{
    double scale = self.slider.value/150.0;
    self.annotationWidth = 52*scale;
    CLLocationCoordinate2D loc = [self.mapView convertPoint:CGPointMake(0, 0) toCoordinateFromView:self.mapView];
    double distance = [TrackTool distanceBetweenOrderByLatitudeA:loc.latitude latitudeB:self.mapView.centerCoordinate.latitude longitudeA:loc.longitude longitudeB:self.mapView.centerCoordinate.longitude];
    double aScale = 1.52/distance;
    if (self.mapView.height==(SCREEN_HEIGHT-538)) {
        aScale = 1.3/distance;
    }
   
    RegionLocationAnnotation *annotationView = (RegionLocationAnnotation *)[self.mapView viewForAnnotation:self.annotation];

    [annotationView setBounds:CGRectMake(0, 0, self.annotationWidth*aScale, self.annotationWidth*aScale)];
    [annotationView.layer setCornerRadius:(self.annotationWidth*aScale)/2];
    [annotationView.location setFrame:CGRectMake((annotationView.width-52)/2, (annotationView.height-52)/2-25, 52, 52)];
        
    self.loCircle.width = self.annotationWidth*aScale;
    self.loCircle.height = self.annotationWidth*aScale;
    [self.loCircle.layer setCornerRadius:(self.annotationWidth*aScale)/2];
    self.loCircle.center = self.mapView.center;
    self.loCircle.y = self.loCircle.y+16;
    
    [self.timer invalidate];
    self.timer = nil;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.5 repeats:NO block:^(NSTimer * _Nonnull timer) {
        [self.timer invalidate];
        self.timer = nil;
                
        CLGeocoder *geocoder = [[CLGeocoder alloc] init];
        CLLocation *location = [[CLLocation alloc] initWithLatitude:self.mapView.centerCoordinate.latitude longitude:self.mapView.centerCoordinate.longitude]; // 示例坐标
        [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
            if (error) {
                {
                    NSMutableDictionary *param = [NSMutableDictionary dictionary];
                    [param setValue:[NSString stringWithFormat:@"%f",self.mapView.centerCoordinate.latitude] forKey:@"lat"];
                    [param setValue:[NSString stringWithFormat:@"%f",self.mapView.centerCoordinate.longitude] forKey:@"lon"];
                    [param setValue:@"1" forKey:@"status"];
                    CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
                    [manager encryptedPOST:@"/apps/data/reversecode"
                    parameters:param
                    success:^(NSDictionary *responseObject) {
                        if ([responseObject[@"code"] integerValue]==200) {
                            self.lastLog.text = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"street"]];
                        }
                    }
                    failure:^(NSError *aError) {
                        
                    }];
                }

            } else {
                if (placemarks.count > 0) {
                    CLPlacemark *placemark = [placemarks objectAtIndex:0];
                    self.lastLog.text = [NSString stringWithFormat:@"%@",placemark.name];
                } else {
                    NSLog(@"No placemarks found.");
                }
            }
        }];
    }];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.locationInfo) {
        return [self.locationInfo[@"usersNotification"] count];
    }else{
        return [self.groupInfo[@"userInfo"] count];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 118;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellIdentifier = @"RegionMemberTableViewCell";
    RegionMemberTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[RegionMemberTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    if (self.locationInfo) {
        [cell loadWithInfo:self.locationInfo[@"usersNotification"][indexPath.row] GroupInfo:self.groupInfo Location:self.locationInfo];
    }else{
        [cell loadWithInfo:self.groupInfo[@"userInfo"][indexPath.row] GroupInfo:self.groupInfo Location:self.locationInfo];
    }
    
    cell.RegionMemberCellBlock = ^(NSInteger code) {
        if (self.locationInfo) {
            [self.locationInfo[@"usersNotification"][indexPath.row] setValue:[NSString stringWithFormat:@"%ld",(long)code] forKey:@"code"];
        }else{
            [self.groupInfo[@"userInfo"][indexPath.row] setValue:[NSString stringWithFormat:@"%ld",(long)code] forKey:@"code"];
        }
        
    };
    return cell;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView == _tableView) {
        CGFloat offsetY = scrollView.contentOffset.y;
            
        if (offsetY > (self.lastContentOffsetY+10)) {
            [UIView animateWithDuration:0.3 animations:^{
                self.infoView.y = SCREEN_HEIGHT-563;
                self.mapView.height = SCREEN_HEIGHT-538;
                self.loImg.center = self.mapView.center;
                self.loCircle.center = self.mapView.center;
                self.loCircle.y = self.loCircle.y+16;
                self.sliderView.y = self.infoView.y-98;
                [self.tableView setFrame:CGRectMake(0, self.line.maxY, SCREEN_WIDTH, SCREEN_HEIGHT-self.infoView.y-self.line.maxY)];
            }];
        } else if (offsetY < (self.lastContentOffsetY-10)) {
            [UIView animateWithDuration:0.3 animations:^{
                self.infoView.y = SCREEN_HEIGHT-413;
                self.mapView.height = SCREEN_HEIGHT-388;
                self.loImg.center = self.mapView.center;
                self.loCircle.center = self.mapView.center;
                self.loCircle.y = self.loCircle.y+16;
                self.sliderView.y = self.infoView.y-98;
                [self.tableView setFrame:CGRectMake(0, self.line.maxY, SCREEN_WIDTH, SCREEN_HEIGHT-self.infoView.y-self.line.maxY)];
            }];
        }
        
        self.lastContentOffsetY = offsetY;
    }
}

- (void)textChangeEvent:(UITextField *)textField
{
    if (textField.text.length>=11) {
        textField.text = [textField.text substringToIndex:11];
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

@end
